package com.vision.world.survey.fragments;

import android.annotation.SuppressLint;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewSwitcher;

import com.esri.arcgisruntime.concurrent.ListenableFuture;
import com.esri.arcgisruntime.geometry.Envelope;
import com.esri.arcgisruntime.geometry.Geometry;
import com.esri.arcgisruntime.mapping.Viewpoint;
import com.esri.arcgisruntime.mapping.view.Graphic;
import com.esri.arcgisruntime.mapping.view.MapView;
import com.vision.world.survey.R;
import com.vision.world.survey.activities.MainActivity;
import com.vision.world.survey.adapters.ResultAdapter;
import com.vision.world.survey.managers.QueryManager;
import com.vision.world.survey.presenter.SettingLayerPresenter;
import com.vision.world.survey.util.CommonUtil;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class BoundaryFragment extends Fragment implements GestureDetector.OnGestureListener {
    ViewSwitcher switcher;
    /**
     * 创建 LayoutInflater 对象
     */
    LayoutInflater mInflater;
    private Context mContext;

    private GestureDetector myDesDet;
    private static Date lastTime = null;
    private MapView mMapView;

    public  ResultAdapter adapter=null;

    public BoundaryFragment(){}

    @SuppressLint({"NewApi", "ValidFragment"})
    public BoundaryFragment(Context context,MapView mapView) {

        // Required empty public constructor
        mContext=context;
        mMapView=mapView;
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_view_switcher, container, false);
        myDesDet = new GestureDetector(this);
        mInflater=inflater;
        adapter=new ResultAdapter(inflater, QueryManager.getInstance().SearchResultFromOperationLayer);
        // 计算应用程序所占的总屏数
        // 如果应用程序的数量能整除NUMBER_PER_SCREEN，除法的结果就是总屏数
        // 如果不能整除，总屏数应该是除法的结果再加 1.
        final List<Map<String,Object>> items= QueryManager.getInstance().SearchResultFromOperationLayer;
        CommonUtil.screenCount = items.size() % CommonUtil.NUMBER_PER_SCREEN == 0 ?
                items.size() / CommonUtil.NUMBER_PER_SCREEN :
                items.size() / CommonUtil.NUMBER_PER_SCREEN + 1;
        switcher = (ViewSwitcher) view.findViewById(R.id.viewSwitcher);
        switcher.setFactory(new ViewSwitcher.ViewFactory() {
            // 实际上就是返回一个GridView组件
            @Override
            public View makeView() {
                View v = mInflater.inflate(R.layout.gv_viewswitch, null);
                GridView img = (GridView) v.findViewById(R.id.gv1);
                img.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                        int a=CommonUtil.screenNo * CommonUtil.NUMBER_PER_SCREEN + i;
                        //设置显示
                        Geometry geo = (Geometry)items.get(a).get(CommonUtil.KEY_GEO);
                        Envelope envelope = geo.getExtent();

                        //设置选中位置居中
                        // mMapView.setViewpointAsync(new Viewpoint(envelope), 2);

                        mMapView.getGraphicsOverlays().get(CommonUtil.IndexGrighicOverlayShowResult).getGraphics().clear();
                        Graphic graphic = new Graphic(geo, CommonUtil.SymbolFill_ShowBoundary);
                        mMapView.getGraphicsOverlays().get(CommonUtil.IndexGrighicOverlayShowResult).getGraphics().add(graphic);
                    }
                });
                // 为图片注册触摸事件监听器
                img.setOnTouchListener(new MyOnTouchListener(myDesDet));
                return v;
            }
        });
        switcher = (ViewSwitcher) view.findViewById(R.id.viewSwitcher);
        // 页面加载时先显示第一屏
        first(null);
        return view;
    }

    public void first(View v) {
        CommonUtil.isIdentify=true;
        Log.i("isFreshIdentify","next");
        if (CommonUtil.screenNo < CommonUtil.screenCount - 1) {
            CommonUtil.screenNo =0;
            // 为ViewSwitcher的组件显示过程设置动画
            switcher.setInAnimation(mContext, R.anim.slide_in_right);
            // 为ViewSwitcher的组件隐藏过程设置动画
            switcher.setOutAnimation(mContext, R.anim.slide_out_left);
            ((GridView)switcher.getNextView()).setAdapter(adapter);
            switcher.showNext();
        }
        CommonUtil.isIdentify=false;
    }

    public void next(View v) {
        CommonUtil.isIdentify=true;
        Log.i("isFreshIdentify","next");
        if (CommonUtil.screenNo < CommonUtil.screenCount - 1) {
            CommonUtil.screenNo ++;
            // 为ViewSwitcher的组件显示过程设置动画
            switcher.setInAnimation(mContext, R.anim.slide_in_right);
            // 为ViewSwitcher的组件隐藏过程设置动画
            switcher.setOutAnimation(mContext, R.anim.slide_out_left);
            ((GridView)switcher.getNextView()).setAdapter(adapter);
            switcher.showNext();
        }
        CommonUtil.isIdentify=false;
    }

    public void prev(View v) {
        CommonUtil.isIdentify=true;
        Log.i("isFreshIdentify","prev");
        if (CommonUtil.screenNo > 0) {
            CommonUtil.screenNo--;
            // 为viewSwitcher的组件显示过程设置动画
            switcher.setInAnimation(mContext, android.R.anim.slide_in_left);
            // 为viewSwitcher的组件隐藏过程设置动画
            switcher.setOutAnimation(mContext, android.R.anim.slide_out_right);
            // 控制下一屏将要显示的GridView对应的Adapter
            ((GridView)switcher.getNextView()).setAdapter(adapter);
            switcher.showPrevious();
        }
        CommonUtil.isIdentify=true;
    }




    @Override
    public boolean onDown(MotionEvent motionEvent) {
        return false;
    }

    @Override
    public void onShowPress(MotionEvent motionEvent) {

    }

    @Override
    public boolean onSingleTapUp(MotionEvent motionEvent) {
        return false;
    }

    @Override
    public boolean onScroll(MotionEvent motionEvent, MotionEvent motionEvent1, float distanceX, float distanceY) {
        // 获取当前时间
        Date curDate = new Date(System.currentTimeMillis());
        float shijiancha = 1000;
        if (lastTime != null)
        {
            shijiancha = curDate.getTime() - lastTime.getTime();
        }
        // 对比两次滑动手势之间的时间间隔。
        // 由于对屏幕的一次滑动可能会被GestureDetector识别到好几次手势，所以需要过滤掉时间间隔太短的手势。
        if (shijiancha > 500)
        {
            if (distanceX > 10)
            {
                Log.i("pull","prev1");
                next(null);
            }
            if (distanceX < -10)
            {
                Log.i("pull","next1");
                prev(null);
            }
        }
        lastTime = curDate;
        return true;
    }

    @Override
    public void onLongPress(MotionEvent motionEvent) {

    }

    @Override
    public boolean onFling(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
        return false;
    }

    /**
     *扩展得到自己的触摸事件监听器
      */
    class MyOnTouchListener implements View.OnTouchListener
    {
        private GestureDetector desDet;
        public MyOnTouchListener(GestureDetector _desDet)
        {
            desDet = _desDet;
        }
        @Override
        public boolean onTouch(View arg0, MotionEvent arg1)
        {
            // 将监听数据传到GestureDetector，GestureDetector可以从中判别手势
            return desDet.onTouchEvent(arg1);
        }
    }
}
